package com.sakura.oj.utils;

import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.exception.BusinessException;
import com.sakura.oj.model.enums.UserRoleEnum;
import com.sakura.oj.model.vo.LoginUserVO;

/**
 * 用户上下文工具类
 */
public class UserHolder {

    private static final ThreadLocal<LoginUserVO> userThreadLocal = new ThreadLocal<>();

    /**
     * 保存用户信息
     *
     * @param user 用户信息
     */
    public static void saveUser(LoginUserVO user) {
        userThreadLocal.set(user);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    public static LoginUserVO getUser() {
        LoginUserVO user = userThreadLocal.get();
        isEmpty(user);
        return user;
    }

    /**
     * 获取用户ID
     *
     * @return 用户ID
     */
    public static Long getUserId() {
        LoginUserVO user = userThreadLocal.get();
        isEmpty(user);
        return user.getId();
    }

    /**
     * 判断是否为管理员
     *
     * @return 是否为管理员
     */
    public static boolean isAdmin() {
        // 仅管理员可查询
        LoginUserVO loginUserVO = getUser();
        return loginUserVO != null && UserRoleEnum.ADMIN.getValue().equals(loginUserVO.getUserRole());
    }

    /**
     * 判断是否为管理员
     *
     * @return 是否为管理员
     */
    public static boolean isNotAdmin() {
        // 仅管理员可查询
        LoginUserVO loginUserVO = getUser();
        return loginUserVO == null || !UserRoleEnum.ADMIN.getValue().equals(loginUserVO.getUserRole());
    }

    /**
     * 清除用户信息
     */
    public static void removeUser() {
        userThreadLocal.remove();
    }

    private static void isEmpty(LoginUserVO loginUserVO) {
        if (loginUserVO == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
    }
} 